package yiran.depositcumulative.command;

import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import org.bukkit.entity.Player;
import org.bukkit.util.StringUtil;
import yiran.depositcumulative.data.DatabaseService;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class CumulativeTabCompleter implements TabCompleter {
    private final DatabaseService databaseService;

    public CumulativeTabCompleter(DatabaseService databaseService) {
        this.databaseService = databaseService;
    }

    @Override
    public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
        if (!command.getName().equalsIgnoreCase("depositcumulative")) {
            return Collections.emptyList();
        }

        // 一级命令补全
        if (args.length == 1) {
            List<String> suggestions = new ArrayList<>();

            // 添加基础命令
            suggestions.add("help");
            suggestions.add("self");
            suggestions.add("all");
            suggestions.add("top");

            // 添加玩家名
            suggestions.addAll(getPlayerSuggestions(args[0]));

            return StringUtil.copyPartialMatches(args[0], suggestions, new ArrayList<>());
        }

        // 二级命令补全（玩家名）
        if (args.length == 2) {
            return getPlayerSuggestions(args[1]);
        }

        return Collections.emptyList();
    }

    private List<String> getPlayerSuggestions(String partialName) {
        List<String> suggestions = new ArrayList<>();

        // 添加在线玩家
        for (Player player : Bukkit.getOnlinePlayers()) {
            if (StringUtil.startsWithIgnoreCase(player.getName(), partialName)) {
                suggestions.add(player.getName());
            }
        }

        // 添加数据库中已充值的玩家
        List<String> depositedPlayers = databaseService.getPlayersWithDeposits();
        for (String player : depositedPlayers) {
            if (StringUtil.startsWithIgnoreCase(player, partialName) &&
                    !suggestions.contains(player)) {
                suggestions.add(player);
            }
        }

        // 按字母排序
        suggestions.sort(String.CASE_INSENSITIVE_ORDER);

        return suggestions;
    }
}
